//
//  NetWorkTool.swift
//  kingWeiBo
//
//  Created by King on 15/9/11.
//  Copyright © 2015年 King. All rights reserved.
//

import UIKit
import AFNetworking

private let kNError = "com.sdq.error"

private enum KNErrorHandle: Int{
    
    case  KNDataError = -1
    case  KNTokenError = -2
    
    private var errorDescription: String{
        switch self{
        case .KNDataError: return "空数据"
        case .KNTokenError: return "token为空"
        }
    
    }
    
    private func error() -> NSError{
        
        return NSError(domain: kNError, code: rawValue, userInfo: [kNError:errorDescription])
    }

}


class NetWorkTool: AFHTTPSessionManager {
    static let shareTools: NetWorkTool = {
        let baseURL = NSURL(string: "https://api.weibo.com/")

        let tool = NetWorkTool(baseURL: baseURL)
        tool.responseSerializer.acceptableContentTypes = NSSet(objects: "application/json", "text/json", "text/javascript", "text/plain") as Set<NSObject>
        return tool
    }()

    
    //Oahth所需字段
    let clientID = "2623088273"
    let redirectUri = "http://www.baidu.com"
    let appSecret = "a7e7a41c5e04ff599c560e2b47ea08f7"
    
    func oauthURL() -> NSURL {
        let othURL = "https://api.weibo.com/oauth2/authorize?client_id=\(clientID)&redirect_uri=\(redirectUri)"

        return NSURL(string: othURL)!
    }
    
    /// 换取TOKEN
    func loadAcessToken(code:String, finished:(result:[String: AnyObject]?,error:NSError?)->()){
        
        let urlSting = "https://api.weibo.com/oauth2/access_token"
        let params = ["client_id": clientID, "client_secret": appSecret,
            "grant_type":"authorization_code", "redirect_uri": redirectUri, "code": code]
        
        POST(urlSting, parameters: params, success: { (_, JSON) -> Void in
            print(JSON)
            
            finished(result: JSON as? [String: AnyObject],error: nil)
            }) { (_, error) -> Void in
                print(error)
        }
    }
    typealias KNNetFinishedCallBack = (result:[String: AnyObject]?,error:NSError?)->()
    
    
    func requestGET(urlString:String, pramas:[String: AnyObject]?, finished: KNNetFinishedCallBack){
    GET(urlString , parameters: pramas, success: { (_, JSON) -> Void in
        if let result = JSON as? [String:AnyObject]{
            finished(result: result, error: nil)
        }else{
            print("没有数据")
            let error = NSError(domain: kNError, code: -1, userInfo: ["errorMessage": "空数据"])
            finished(result: nil, error: error)
        }
        }) { (_, error) -> Void in
            finished(result: nil, error: error)
        }
    }
    //MARK: - 生成token字典
    func tokenDict(finished: KNNetFinishedCallBack) -> [String: AnyObject]?{
        if userAccount.shareAccount?.access_token == nil{
            
            let errors = KNErrorHandle.KNTokenError.error()
            
            finished(result: nil, error: errors)
            return nil
            
        }
        return ["access_token": userAccount.shareAccount!.access_token!]
        
    }
    
    
    //MARK: - 加载微博数据
    func loadWeiBoData(finished: KNNetFinishedCallBack){
        
        guard let params = tokenDict(finished) else{
            return
        }
        
        let urlString = "2/statuses/home_timeline.json"

        requestGET(urlString, pramas: params, finished: finished)

        
    
    }
    /// 加载用户信息
    func loadUserInfo(uid:String,finished:KNNetFinishedCallBack ){
        
        guard var params = tokenDict(finished) else{
            return
        }

        
        let urlString = "2/users/show.json"

        params["uid"] = uid
        requestGET(urlString, pramas: params, finished: finished)
    
    }
}
